import React, {PureComponent} from 'react';
import {connect} from 'react-redux';
import {Card, Divider, Icon, Modal, notification, Timeline, TreeSelect} from 'antd';
import {ChartCard, Field, MiniArea, MiniBar} from 'ant-design-pro/lib/Charts';
import numeral from 'numeral';
import {changeOrganization, getCurrentOrganization, getOrganizationTree, getPrincipal} from "../../lib/identity";
import {showCreate} from "../notes/actions";
import 'ant-design-pro/dist/ant-design-pro.css'; // 统一引入样式
import {
    containerOrderList,
    countByName,
    daiBanShiXiangData,
    delNote,
    fixNote,
    getContainerOrderExpiredList,
    getContractExpireList,
    getLog,
    getOrderExpiredList,
    getOrderNoCompletedList,
    lastMonthOrderCountAndAmount,
    noteList,
    organizations,
    queryNotice,
    thisMonthOrderCountAndMoney,
    todayOrderCountAndMoney
} from "./actions";
import DaiBanInfo from "../../components/DaiBanInfo";
import lodash from 'lodash';

const TreeNode = TreeSelect.TreeNode;

const renderTreeNodes = (dataSource) => {

    return dataSource && dataSource.map((item) => {
        if (item.children) {
            return (<TreeNode title={item.name} key={item.id} value={item.id}>
                {renderTreeNodes(item.children)}
            </TreeNode>);
        }
        return <TreeNode title={item.name} key={item.id} value={item.id}/>;
    });
};

class Home extends PureComponent {
    componentDidMount() {
        const {dispatch} = this.props;
        const principal = getPrincipal();
        dispatch(noteList({"userId": principal.id, "orgId": getCurrentOrganization()}));
        dispatch(queryNotice(getCurrentOrganization()));
        dispatch(getLog({"userId": principal.id, "orgId": getCurrentOrganization()}));
        dispatch(containerOrderList({"userId": principal.id, "orgId": getCurrentOrganization()}));
        dispatch(todayOrderCountAndMoney({"userId": principal.id, "orgId": getCurrentOrganization()}));
        dispatch(thisMonthOrderCountAndMoney({"userId": principal.id, "orgId": getCurrentOrganization()}));
        dispatch(countByName());
        dispatch(lastMonthOrderCountAndAmount({"userId": principal.id, "orgId": getCurrentOrganization()}));
        dispatch(getOrderExpiredList({"userId": principal.id, "orgId": getCurrentOrganization()}));
        dispatch(getContainerOrderExpiredList({"userId": principal.id, "orgId": getCurrentOrganization()}));
        dispatch(getOrderNoCompletedList({"userId": principal.id, "orgId": getCurrentOrganization()}));
        dispatch(getContractExpireList({"userId": principal.id, "orgId": getCurrentOrganization()}));
        dispatch(daiBanShiXiangData({"userId": principal.id, "orgId": getCurrentOrganization()}));
        dispatch(organizations(principal.id));
    }

    addNote = () => {
        const {dispatch} = this.props;
        dispatch(showCreate());
    };

    handleFixed = (id) => {
        const {dispatch} = this.props;
        const principal = getPrincipal();
        dispatch(fixNote(id)).then(action => {
            if (action.error !== true) {
                dispatch(noteList(principal.id));
                notification.success({
                    message: '已办成功'
                });
            }
        });
    };


    handleDeleteNote = (id) => {
        const {dispatch} = this.props;
        const principal = getPrincipal();
        dispatch(delNote(id)).then(action => {
            if (action.error !== true) {
                dispatch(noteList(principal.id));
                notification.success({
                    message: '删除成功'
                });
            }
        });
    };

    handleFunc = route => {
        this.props.history.push(route);
    };

    onOrganizationChange = orgId => {
        changeOrganization(orgId);
        window.location.reload();
    };

    noticeInfo = (title, content) => {
        Modal.info({
            title: title, content: (<div>
                {content}
            </div>), onOk() {
            },
        });
    };

    render() {
        const {
            noteList,
            logs,
            noticeList,
            todayOrderCountAndMoney,
            lastMonthData,
            daiBanShiXiangList,
            thisMonthOrderCountAndMoney,
            countByBusinessType,
            contractExpireList,
            containerOrderExpiredList,
            orderExpiredList,
            orderNoCompletedList,
            countByOriginPlace,
            countByName
        } = this.props;
        const permissions = getPrincipal().permissions || [];
        const canCheckData = getPrincipal().canCheckData || [];
        const organizations = getOrganizationTree() || [];
        const flag = permissions.indexOf("内部公告") >= 0 || getPrincipal().admin;
        // 饼图
        const originPlaceData = [];
        countByOriginPlace.forEach(item => {
            originPlaceData.push({
                type: item.originPlace, value: item.count
            });
        });

        const group_logs = lodash.groupBy(logs, "date");
        const new_group = [];
        for (let date in group_logs) {
            new_group.push({"date": date, "data": group_logs[date]});
        }

        // 格式化数字
        const formatToFixed = (money, decimals = 2) => {
            return (Math.round((parseFloat(money) + Number.EPSILON) * Math.pow(10, decimals)) / Math.pow(10, decimals)).toFixed(decimals);
        };
        const formatMoney = (money, symbol = "", decimals = 2) => `${symbol}${parseFloat(formatToFixed(money, decimals)).toLocaleString()}`;

        const visitData = [];

        const config = {
            forceFit: true, title: {
                visible: true, text: '多色饼图',
            }, radius: 0.8, data: originPlaceData, angleField: 'value', colorField: 'type', label: {
                visible: true, type: 'inner',
            },
        };

        //柱状图
        const businessData = [];
        let count = 0;
        lastMonthData.forEach(item => {
            businessData.push({
                type: item.name, sales: item.count
            });
            visitData.push({
                x: item.name, y: item.count
            });
            count += item.count;
        });
        const businessDataConfig = {
            title: {
                visible: true, text: '基础柱状图-图形标签位置',
            }, forceFit: true, data: businessData, padding: 'auto', xField: 'type', yField: 'sales', meta: {
                type: {alias: '类别'}, sales: {alias: '单量'},
            }, label: {
                visible: true, position: 'middle',
            }
        };

        // 线路对比
        const carrierLineData = [];
        const clientLineData = [];
        countByName.forEach(item => {
            if ("OUT" === item.type) {
                const name = item.name;
                item.placeCounts.forEach(da => {
                    carrierLineData.push({
                        date: name, type: da.place, value: da.count
                    });
                });
            } else {
                const name = item.name;
                item.placeCounts.forEach(da => {
                    clientLineData.push({
                        date: name, type: da.place, value: da.count
                    });
                });
            }
        });
        const yingShouData = [];
        let amount = 0.00;
        lastMonthData.forEach(item => {
            /*yingShouData.push({
                type: item.name,
                '金额': item.amount
            });*/
            yingShouData.push({
                x: item.name, y: item.amount
            });
            amount += item.amount;
        });
        const bgFileData = [];
        const orderConfirmData = [];
        const suiCheData = [];
        const packageSolutionData = [];
        const stData = [];
        const transportOrderData = [];
        const bgReleaseData = [];
        const noArriveData = [];
        const weightData = [];
        const zhuangxiangData = [];
        daiBanShiXiangList.forEach(item => {
            const array = item.split(" ");
            const orderNumber = array[0];
            if (array[1].indexOf("未提供报关文件") >= 0) {
                if (bgFileData.indexOf(orderNumber) === -1) {
                    bgFileData.push(orderNumber);
                }
            }
            if (array[1].indexOf("未确认预录单") >= 0) {
                if (orderConfirmData.indexOf(orderNumber) === -1) {
                    orderConfirmData.push(orderNumber);
                }
            }
            if (array[1].indexOf("未提供随车文件") >= 0) {
                if (suiCheData.indexOf(orderNumber) === -1) {
                    suiCheData.push(orderNumber);
                }
            }
            if (array[1].indexOf("未提供装箱方案") >= 0) {
                if (packageSolutionData.indexOf(orderNumber) === -1) {
                    packageSolutionData.push(orderNumber);
                }
            }
            if (array[1].indexOf("未提供ST文件") >= 0) {
                if (stData.indexOf(orderNumber) === -1) {
                    stData.push(orderNumber);
                }
            }
            if (array[1].indexOf("未提供运单") >= 0) {
                if (transportOrderData.indexOf(orderNumber) === -1) {
                    transportOrderData.push(orderNumber);
                }
            }
            if (array[1].indexOf("未提供报关放行单") >= 0) {
                if (bgReleaseData.indexOf(orderNumber) === -1) {
                    bgReleaseData.push(orderNumber);
                }
            }
            if (array[1].indexOf("未到站") >= 0) {
                if (noArriveData.indexOf(orderNumber) === -1) {
                    noArriveData.push(orderNumber);
                }
            }
            if (array[1].indexOf("未提供提重文件") >= 0) {
                if (weightData.indexOf(orderNumber) === -1) {
                    weightData.push(orderNumber);
                }
            }
            if (array[1].indexOf("未提供装箱图片") >= 0) {
                if (zhuangxiangData.indexOf(orderNumber) === -1) {
                    zhuangxiangData.push(orderNumber);
                }
            }
        });
        const invoiceList = [];
        const settlementList = [];
        const outInvoiceList = [];
        const outSettlementList = [];
        orderExpiredList.forEach(item => {
            if (item.indexOf("应收未开票") >= 0) {
                invoiceList.push(item.split(" ")[0]);
            }
            if (item.indexOf("应收未结算") >= 0) {
                settlementList.push(item.split(" ")[0]);
            }
            if (item.indexOf("应付未开票") >= 0) {
                outInvoiceList.push(item.split(" ")[0]);
            }
            if (item.indexOf("应付未结算") >= 0) {
                outSettlementList.push(item.split(" ")[0]);
            }
        });
        return (<div>
            {(getPrincipal().admin || canCheckData.indexOf("订单量") >= 0 || canCheckData.indexOf("上月单量数据") >= 0 || canCheckData.indexOf("营收") >= 0 || canCheckData.indexOf("上月营收数据") >= 0) &&
                <div>
                    <div style={{padding: '10px', width: '50%', height: "169px", float: 'left'}}>
                        {(canCheckData.indexOf("订单量") >= 0 || flag) &&
                            <div style={{width: '40%', height: "170px", float: 'left'}}>
                                <Card title={"订单量"} bordered={false}
                                      style={{width: '100%', height: '100%', float: 'left'}}>
                                    <h5 style={{fontWeight: "bolder"}}>国际班列{formatMoney(thisMonthOrderCountAndMoney.blCount)}单</h5>
                                    <h5 style={{fontWeight: "bolder"}}>综合物流{formatMoney(thisMonthOrderCountAndMoney.ghCount)}单</h5>
                                    <h3 style={{fontWeight: "bolder"}}>当月累计 {formatMoney(thisMonthOrderCountAndMoney.count)}单</h3>
                                </Card>
                            </div>}
                        <div style={{width: '2%', height: "100%", float: 'left'}}>
                            <Divider type={"vertical"}/>
                        </div>
                        {(canCheckData.indexOf("上月单量数据") >= 0 || flag) &&
                            <div style={{width: '55%', float: 'left', height: "170px"}}>
                                <ChartCard
                                    style={{width: '100%', float: 'left', height: "100%"}}
                                    title="上月单量数据"
                                    footer={<Field label="单量总数" value={numeral(count).format('0,0') + "单"}/>}
                                    contentHeight={70}
                                >
                                    <MiniBar height={70} data={visitData}/>
                                </ChartCard>
                            </div>}
                    </div>
                    <div style={{padding: '10px', width: '50%', float: 'left'}}>
                        {(canCheckData.indexOf("营收") >= 0 || flag) &&
                            <div style={{width: '40%', height: "170px", float: 'left'}}>
                                <Card title={"营收"} bordered={false} style={{width: '100%', height: '100%'}}>
                                    <h5 style={{fontWeight: "bolder"}}>国际班列￥{thisMonthOrderCountAndMoney.blAmount && formatMoney(thisMonthOrderCountAndMoney.blAmount)}</h5>
                                    <h5 style={{fontWeight: "bolder"}}>综合物流￥{thisMonthOrderCountAndMoney.ghAmount && formatMoney(thisMonthOrderCountAndMoney.ghAmount)}</h5>
                                    <h3 style={{fontWeight: "bolder"}}>当月累计
                                        ￥{thisMonthOrderCountAndMoney.amount && formatMoney(thisMonthOrderCountAndMoney.amount)}</h3>
                                </Card>
                            </div>}
                        <div style={{width: '2%', height: "100px", float: 'left'}}>
                            <Divider type={"vertical"}/>
                        </div>
                        {(canCheckData.indexOf("上月营收数据") >= 0 || flag) &&
                            <div style={{width: '55%', float: 'left', height: "170px"}}>
                                <ChartCard
                                    style={{width: '100%', float: 'left', height: "100%"}}
                                    title="上月营收数据"
                                    footer={<Field label="总营收" value={"￥" + amount.toFixed(2)}/>}
                                    contentHeight={70}
                                >
                                    <MiniArea line height={70} data={yingShouData}/>
                                </ChartCard>
                            </div>}
                    </div>
                    <Divider/>
                </div>}
            <div style={{height: "300px"}}>
                {(flag || canCheckData.indexOf("内部公告") >= 0) &&
                    <div style={{padding: '10px', float: 'left', width: "60%"}}>
                        <Card title="内部公告" bordered={false} style={{width: "100%"}}
                              extra={<a onClick={() => this.handleFunc("/historyNotice")}>历史公告</a>}>
                            <div style={{height: "300px", overflow: "auto"}}>
                                {containerOrderExpiredList && containerOrderExpiredList.map(item => {
                                    return <div style={{width: "100%"}}>{item}</div>
                                })}
                                {noticeList && noticeList.map((item, index) => {
                                    return <div style={{width: "100%", cursor: 'pointer'}}
                                                onClick={() => this.noticeInfo(item.title, item.description)}>
                                        <span style={{color: "blue"}}>
                                        <Icon
                                            type="notification"/>{" 系统通知" + (index + 1) + "：标题：" + item.title + " 公告有效期：" + item.startTime + " 至 " + item.endTime}
                                    </span>
                                    </div>
                                })}
                                {contractExpireList && contractExpireList.map(item => {
                                    return <div style={{width: "100%"}}>{item}</div>
                                })}
                            </div>
                        </Card>
                    </div>}
                <div style={{padding: '10px', height: "300px", width: "40%", float: 'left'}}>
                    <Card title="操作日志" bordered={false}>
                        <div style={{height: "300px", overflow: "auto"}}>
                            {new_group.map(item => {
                                return <div>
                                    <h3>{item.date}</h3>
                                    <Timeline>
                                        {item.data && item.data.map(item => {
                                            return <Timeline.Item>{item.time + " " + item.userName + " | " + item.content + " |" +
                                                " " + item.targetId}</Timeline.Item>
                                        })}
                                    </Timeline>
                                </div>
                            })}

                        </div>
                    </Card>
                </div>
            </div>
            <Divider style={{marginTop: "90px"}}/>
            <h3 style={{color: "red"}}><Icon type="pushpin"/>待办事项</h3>
            <div style={{width: "100%"}}>
                {(canCheckData.indexOf("班列订单未完成") >= 0 || flag) &&
                    <div style={{width: "20%", padding: '10px', float: 'left'}}>
                        <Card title={"班列订单未完成"} bordered={false}
                              style={{width: '100%'}}
                              extra={<a onClick={() => this.handleFunc("/zadOrder")}>前往</a>}>
                            <h1 style={{fontWeight: "bolder"}}>{orderNoCompletedList.length}单 <DaiBanInfo
                                item={orderNoCompletedList}/></h1>
                        </Card>
                    </div>}
                {(canCheckData.indexOf("应收未开票") >= 0 || flag) &&
                    <div style={{width: "20%", padding: '10px', float: 'left'}}>
                        <Card title={"应收未开票"} bordered={false}
                              style={{width: '100%'}}
                              extra={<div><a onClick={() => this.handleFunc("/zadOrderReceivable")}>班列</a><a
                                  style={{marginLeft: "10px"}}
                                  onClick={() => this.handleFunc("/ghOrderReceivable")}>综合物流</a></div>}>
                            <h1 style={{fontWeight: "bolder"}}>{invoiceList.length}单 <DaiBanInfo
                                item={invoiceList}/></h1>
                        </Card>
                    </div>}
                {(canCheckData.indexOf("应收未结算") >= 0 || flag) &&
                    <div style={{width: "20%", padding: '10px', float: 'left'}}>
                        <Card title={"应收未结算"} bordered={false}
                              style={{width: '100%'}}
                              extra={<div><a onClick={() => this.handleFunc("/zadOrderReceivable")}>班列</a><a
                                  style={{marginLeft: "10px"}}
                                  onClick={() => this.handleFunc("/ghOrderReceivable")}>综合物流</a></div>}>
                            <h1 style={{fontWeight: "bolder"}}>{settlementList.length}单 <DaiBanInfo
                                item={settlementList}/></h1>
                        </Card>
                    </div>}
                {(canCheckData.indexOf("应付未开票") >= 0 || flag) &&
                    <div style={{width: "20%", padding: '10px', float: 'left'}}>
                        <Card title={"应付未开票"} bordered={false}
                              style={{width: '100%'}}
                              extra={<div><a onClick={() => this.handleFunc("/zadOrderPayable")}>班列</a><a
                                  style={{marginLeft: "10px"}}
                                  onClick={() => this.handleFunc("/ghOrderPayable")}>综合物流</a></div>}>
                            <h1 style={{fontWeight: "bolder"}}>{outInvoiceList.length}单 <DaiBanInfo
                                item={outInvoiceList}/></h1>
                        </Card>
                    </div>}
                {(canCheckData.indexOf("应付未结算") >= 0 || flag) &&
                    <div style={{width: "20%", padding: '10px', float: 'left'}}>
                        <Card title={"应付未结算"} bordered={false}
                              style={{width: '100%'}}
                              extra={<div><a onClick={() => this.handleFunc("/zadOrderPayable")}>班列</a><a
                                  style={{marginLeft: "10px"}}
                                  onClick={() => this.handleFunc("/ghOrderPayable")}>综合物流</a></div>}>
                            <h1 style={{fontWeight: "bolder"}}>{outSettlementList.length}单 <DaiBanInfo
                                item={outSettlementList}/></h1>
                        </Card>
                    </div>}
            </div>
            <Divider/>
            <h3 style={{color: "red"}}><Icon type="pushpin"/>单据待处理</h3>
            <div style={{width: "100%"}}>
                {bgFileData && bgFileData.length > 0 && <div style={{width: "20%", padding: '10px', float: 'left'}}>
                    <Card title={"未提供报关文件"} bordered={false}
                          style={{width: '100%'}}>
                        <h1 style={{fontWeight: "bolder"}}>{bgFileData.length}单 <DaiBanInfo
                            item={bgFileData}/></h1>
                    </Card>
                </div>}
                {orderConfirmData && orderConfirmData.length > 0 &&
                    <div style={{width: "20%", padding: '10px', float: 'left'}}>
                        <Card title={"未确认预录单"} bordered={false}
                              style={{width: '100%'}}>
                            <h1 style={{fontWeight: "bolder"}}>{orderConfirmData.length}单 <DaiBanInfo
                                item={orderConfirmData}/></h1>
                        </Card>
                    </div>}
                {suiCheData && suiCheData.length > 0 && <div style={{width: "20%", padding: '10px', float: 'left'}}>
                    <Card title={"未提供随车文件"} bordered={false}
                          style={{width: '100%'}}>
                        <h1 style={{fontWeight: "bolder"}}>{suiCheData.length}单 <DaiBanInfo
                            item={suiCheData}/></h1>
                    </Card>
                </div>}
                {packageSolutionData && packageSolutionData.length > 0 &&
                    <div style={{width: "20%", padding: '10px', float: 'left'}}>
                        <Card title={"未提供装箱方案"} bordered={false}
                              style={{width: '100%'}}>
                            <h1 style={{fontWeight: "bolder"}}>{packageSolutionData.length}单 <DaiBanInfo
                                item={packageSolutionData}/></h1>
                        </Card>
                    </div>}
                {stData && stData.length > 0 && <div style={{width: "20%", padding: '10px', float: 'left'}}>
                    <Card title={"未提供ST文件"} bordered={false}
                          style={{width: '100%'}}>
                        <h1 style={{fontWeight: "bolder"}}>{stData.length}单 <DaiBanInfo
                            item={stData}/></h1>
                    </Card>
                </div>}
                {transportOrderData && transportOrderData.length > 0 &&
                    <div style={{width: "20%", padding: '10px', float: 'left'}}>
                        <Card title={"未提供运单"} bordered={false}
                              style={{width: '100%'}}>
                            <h1 style={{fontWeight: "bolder"}}>{transportOrderData.length}单 <DaiBanInfo
                                item={transportOrderData}/></h1>
                        </Card>
                    </div>}
                {bgReleaseData && bgReleaseData.length > 0 &&
                    <div style={{width: "20%", padding: '10px', float: 'left'}}>
                        <Card title={"未提供报关放行单"} bordered={false}
                              style={{width: '100%'}}>
                            <h1 style={{fontWeight: "bolder"}}>{bgReleaseData.length}单 <DaiBanInfo
                                item={bgReleaseData}/></h1>
                        </Card>
                    </div>}
                {noArriveData && noArriveData.length > 0 && <div style={{width: "20%", padding: '10px', float: 'left'}}>
                    <Card title={"未到站"} bordered={false}
                          style={{width: '100%'}}>
                        <h1 style={{fontWeight: "bolder"}}>{noArriveData.length}单 <DaiBanInfo
                            item={noArriveData}/></h1>
                    </Card>
                </div>}
                {weightData && weightData.length > 0 && <div style={{width: "20%", padding: '10px', float: 'left'}}>
                    <Card title={"未提供提重文件"} bordered={false}
                          style={{width: '100%'}}>
                        <h1 style={{fontWeight: "bolder"}}>{weightData.length}单 <DaiBanInfo
                            item={weightData}/></h1>
                    </Card>
                </div>}
                {zhuangxiangData && zhuangxiangData.length > 0 &&
                    <div style={{width: "20%", padding: '10px', float: 'left'}}>
                        <Card title={"未提供装箱图片"} bordered={false}
                              style={{width: '100%'}}>
                            <h1 style={{fontWeight: "bolder"}}>{zhuangxiangData.length}单 <DaiBanInfo
                                item={zhuangxiangData}/></h1>
                        </Card>
                    </div>}
            </div>
        </div>);
    }
}

const mapStateToProps = state => {
    return {
        ...state.home
    };
};

export default connect(mapStateToProps)(Home);
